package com.demo.controller;

import cn.hutool.core.util.IdUtil;
import com.demo.common.ResultData;
import com.demo.config.datasource.annotation.DS;
import com.demo.config.datasource.annotation.DynamicDSEnum;
import com.demo.entity.TestEntity;
import com.demo.mapper.Test1Mapper;
import com.demo.mapper.TestMapper;
import com.demo.service.TestService;
import com.demo.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 多数据源
 *
 * @author wangfengchen
 */
@Slf4j
@RestController
@RequestMapping("/data-soure")
public class MultipleDataSourceController {


  @Autowired
  private TestMapper testMapper;
  @Autowired
  private Test1Mapper test1Mapper;
  //  @Autowired
//  private Test2Mapper test2Mapper;
  @Autowired
  private TestService testService;
  @Autowired
  private UserService userService;






  /**
   * 第一种方式
   * 多数据源事物不会回滚，需要使用分布式事务
   * 注意：需要指定扫描包和使用哪个 sqlSessionFactory，mapper必须放在不同的两个包下，
   * 比如 Test1Mapper 和 Test2Mapper 分别放在 com.demo.mapper 和 com.demo.mapper2 下才行
   * 如果使用需要放开 config 中 multiple 里面的代码
   *
   * @return
   */
//  @Transactional(rollbackFor = Exception.class)
//  @GetMapping("/transaction")
//  public ResultData transaction() {
//    TestEntity testEntity = new TestEntity();
//    testEntity.setId(IdUtil.getSnowflakeNextId());
//    testEntity.setUsername(IdUtil.getSnowflakeNextIdStr());
//    testEntity.setAge(18);
//    test1Mapper.insert(testEntity);
//    test2Mapper.insert(testEntity);
//    int i = 1 / 0;
//    return ResultData.success();
//  }

  /**
   * 第二种方式，注解方式
   * 不写 DS 默认就是 master
   *
   * @return
   */
  @Transactional(rollbackFor = Exception.class)
  @GetMapping("/master")
  public ResultData master() {
    TestEntity testEntity = new TestEntity();
    testEntity.setId(IdUtil.getSnowflakeNextId());
    testEntity.setUsername(IdUtil.getSnowflakeNextIdStr());
    testEntity.setAge(18);
    testMapper.insert(testEntity);
    int i = 1 / 0;
    return ResultData.success();
  }


  @DS(DynamicDSEnum.SLAVE)
  @Transactional(rollbackFor = Exception.class)
  @GetMapping("/slave")
  public ResultData slave() {
    TestEntity testEntity = new TestEntity();
    testEntity.setId(IdUtil.getSnowflakeNextId());
    testEntity.setUsername(IdUtil.getSnowflakeNextIdStr());
    testEntity.setAge(18);
    testMapper.insert(testEntity);
//    int i = 1 / 0;
    return ResultData.success();
  }

  /**
   * 手动切换数据源
   * 注意：一个事务内不支持切换数据源（事务绑定到初始数据源）
   * 如果想要切换数据源需要注释掉事务注解
   *
   * @return
   */
  @Transactional(rollbackFor = Exception.class)
  @GetMapping("/change")
  public ResultData change() {
    testService.add();
    userService.add2();
    return ResultData.success();
  }


}
